package com.LachesismStorm.lachesism.core.email;

import com.LachesismStorm.lachesism.core.util.LachesismTools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import static com.LachesismStorm.lachesism.core.common.enums.CommonEnum.DATE_FORMATTER;
import static com.LachesismStorm.lachesism.core.util.LachesismTools.*;

@Component
public class EmailUtil {

    // 邮箱配置
    @Value("${email.qq.host}")
    private String qqHost;
    @Value("${email.qq.port}")
    private String qqPort;
    @Value("${email.qq.username}")
    private String qqUsername;
    @Value("${email.qq.password}")
    private String qqPassword;

    @Value("${email.google.host}")
    private String googleHost;
    @Value("${email.google.port}")
    private String googlePort;
    @Value("${email.google.username}")
    private String googleUsername;
    @Value("${email.google.password}")
    private String googlePassword;

    @Value("${email.163.host}")
    private String neteaseHost;
    @Value("${email.163.port}")
    private String neteasePort;
    @Value("${email.163.username}")
    private String neteaseUsername;
    @Value("${email.163.password}")
    private String neteasePassword;

    private Properties properties;

    // 通过邮箱服务来配置不同的 SMTP 设置
    private void configureProperties(String host, String port, String username, String password) {
        properties = new Properties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port); // 支持的端口
        properties.setProperty("mail.smtp.auth", "true"); // 是否需要认证
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 启用STARTTLS加密
    }

    // 获取指定邮箱服务的配置
    private void getEmailServiceConfig(String emailService, EmailServiceConfig config) {
        switch (emailService) {
            case "qq":
                config.setHost(qqHost);
                config.setPort(qqPort);
                config.setUsername(qqUsername);
                config.setPassword(qqPassword);
                break;
            case "google":
                config.setHost(googleHost);
                config.setPort(googlePort);
                config.setUsername(googleUsername);
                config.setPassword(googlePassword);
                break;
            case "netease":
                config.setHost(neteaseHost);
                config.setPort(neteasePort);
                config.setUsername(neteaseUsername);
                config.setPassword(neteasePassword);
                break;
            default:
                throw new IllegalArgumentException("不支持的邮箱服务");
        }
    }

    // 发送邮件（普通邮件）
    public boolean sendEmail(String emailService, String to, String subject, String content) {
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 创建邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功!");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 发送带 HTML 内容的邮件
    public boolean sendHtmlEmail(String emailService, String to, String subject, String htmlFilePath) {
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 读取资源目录下的 HTML 文件内容
        StringBuilder htmlContent = new StringBuilder();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(htmlFilePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("HTML 文件未找到: " + htmlFilePath);
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = br.readLine()) != null) {
                    htmlContent.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取 HTML 文件时出错: " + e.getMessage());
            return false;
        }

        // 创建邮件消息
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setContent(htmlContent.toString().replace("#验证码#", "验证码：1234"), "text/html; charset=utf-8");

            // 发送邮件
            Transport.send(message);
            System.out.println("HTML 邮件发送成功!");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件时出错: " + e.getMessage());
            return false;
        }
    }

    // 发送本地磁盘上的 HTML 内容的邮件
    public boolean sendHtmlEmailOnDisk(String emailService, String to, String subject, String htmlFilePath) {
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 读取磁盘路径下的 HTML 文件内容
        StringBuilder htmlContent = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(htmlFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                htmlContent.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取 HTML 文件时出错: " + e.getMessage());
            return false;
        }

        // 创建邮件消息
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setContent(htmlContent.toString(), "text/html; charset=utf-8");
            // 发送邮件
            Transport.send(message);
            System.out.println("HTML 邮件发送成功!");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件时出错: " + e.getMessage());
            return false;
        }
    }


    // 发送带附件的邮件
    public boolean sendEmailWithAttachment(String emailService, String to, String subject, String content, String attachmentPath) {
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 创建邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // 创建邮件内容部分
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(content);

            // 创建附件部分
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.attachFile(attachmentPath);

            // 合并邮件正文和附件
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);

            // 设置邮件内容
            message.setContent(multipart);

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件（带附件）发送成功!");
            return true;
        } catch (MessagingException | java.io.IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 发送带附件的邮件（带图片URL附件）
    public void sendEmailWithAttachmentOnline(String emailService, String to, String subject, String content, String imageUrl) {
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 创建邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            // 创建邮件内容部分
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(content);
            // 获取图片URL并作为附件
            MimeBodyPart attachmentPart = new MimeBodyPart();
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();
            // 使用 ByteArrayDataSource 来处理图片
            ByteArrayDataSource dataSource = new ByteArrayDataSource(inputStream, "image/png");
            attachmentPart.setDataHandler(new DataHandler(dataSource));
            attachmentPart.setFileName(getTime(DATE_FORMATTER) + "日老黄历分析.png");
            // 合并邮件正文和附件
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);
            // 设置邮件内容
            message.setContent(multipart);
            // 发送邮件
            Transport.send(message);
            System.out.println("邮件（带附件）发送成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMissEmail(String emailService, String to, String subject, String htmlFilePath, String value) {
        System.out.println("发送短信了");
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);
        String newHtmlContent = "";

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 读取资源目录下的 HTML 文件内容
        StringBuilder htmlContent = new StringBuilder();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(htmlFilePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("HTML 文件未找到: " + htmlFilePath);
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = br.readLine()) != null) {
                    htmlContent.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取 HTML 文件时出错: " + e.getMessage());
        }
        // 替换星座信息
        newHtmlContent = htmlContent.toString().replace("#datetime#", value);
        // 创建邮件消息
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);

            // 设置邮件内容，确保只设置一次
            message.setContent(newHtmlContent, "text/html; charset=utf-8");
            // 发送邮件
            Transport.send(message);
            System.out.println("HTML 邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件时出错: " + e.getMessage());
        }
    }

    public void sendGroupEmailOnConstellation(String emailService, String to, String subject, String htmlFilePath, Object obj) {
        EmailServiceConfig config = new EmailServiceConfig();
        getEmailServiceConfig(emailService, config);
        String newHtmlContent = "";

        // 配置 SMTP 设置
        configureProperties(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());

        // 读取资源目录下的 HTML 文件内容
        StringBuilder htmlContent = new StringBuilder();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(htmlFilePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("HTML 文件未找到: " + htmlFilePath);
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = br.readLine()) != null) {
                    htmlContent.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取 HTML 文件时出错: " + e.getMessage());
        }
        // 替换星座信息
        newHtmlContent = replaceConstellationInfo(htmlContent.toString(), obj);

        // 创建邮件消息
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getUsername()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);

            // 设置邮件内容，确保只设置一次
            message.setContent(newHtmlContent, "text/html; charset=utf-8");
            // 发送邮件
            Transport.send(message);
            System.out.println("HTML 邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件时出错: " + e.getMessage());
        }
    }

    private String replaceConstellationInfo(String htmlContent, Object obj) {
        JSONObject jsonObject = (JSONObject) JSON.toJSON(obj);
        // 获取需要的 JSON 对象
        JSONObject today = jsonObject.getJSONObject("today");
        JSONObject tomorrow = jsonObject.getJSONObject("tomorrow");
        JSONObject week = jsonObject.getJSONObject("week");
        JSONObject mouth = jsonObject.getJSONObject("mouth");
        JSONObject year = jsonObject.getJSONObject("year");
        // 创建占位符到值的映射
        Map<String, String> replacementMap = new HashMap<>();
        replacementMap.put("#年月日#", getTime(DATE_FORMATTER));
        String replace = getZodiacSign()[1];
        replacementMap.put("#星座月#", replace);
        replacementMap.put("#星座月图片链接#", "https://www.yunox.cn/image/" + getZodiacSign()[0] + ".png");
        replacementMap.put("#今日时间#", getTime(DATE_FORMATTER));
        replacementMap.put("#明日时间#", getTomorrowTime(DATE_FORMATTER));
        replacementMap.put("#今日综合指数#", today.getString("all"));
        replacementMap.put("#今日健康指数#", today.getString("health"));
        replacementMap.put("#今日爱情指数#", today.getString("love"));
        replacementMap.put("#今日财运指数#", today.getString("money"));
        replacementMap.put("#今日概述#", today.getString("summary"));
        replacementMap.put("#明日综合指数#", tomorrow.getString("all"));
        replacementMap.put("#明日健康指数#", tomorrow.getString("health"));
        replacementMap.put("#明日爱情指数#", tomorrow.getString("love"));
        replacementMap.put("#明日财运指数#", tomorrow.getString("money"));
        replacementMap.put("#明日总结#", tomorrow.getString("summary"));
        replacementMap.put("#本周时间范围#", week.getString("date"));
        replacementMap.put("#本周健康运势#", week.getString("health"));
        replacementMap.put("#本周爱情指数#", week.getString("love"));
        replacementMap.put("#本周财运指数#", week.getString("money"));
        replacementMap.put("#本周工作指数#", week.getString("work"));
        replacementMap.put("#本月日期#", mouth.getString("date"));
        replacementMap.put("#本月综合运势#", mouth.getString("all"));
        replacementMap.put("#本月健康运势#", mouth.getString("health"));
        replacementMap.put("#本月爱情运势#", mouth.getString("love"));
        replacementMap.put("#本月财运运势#", mouth.getString("money"));
        replacementMap.put("#今年时间#", year.getString("date"));
        replacementMap.put("#今年总结#", year.getString("all"));
        replacementMap.put("#今年健康指数#", year.getString("health"));
        replacementMap.put("#今年感情运#", year.getString("love"));
        replacementMap.put("#今年财运#", year.getString("money"));
        replacementMap.put("#今年总结2#", year.getString("summary"));
        // 遍历 map 中的所有映射，进行替换
        for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
            htmlContent = htmlContent.replace(entry.getKey(), entry.getValue());
        }
        return htmlContent;
    }


    // 邮箱服务的配置信息
    private static class EmailServiceConfig {
        private String host;
        private String port;
        private String username;
        private String password;

        // Getters and Setters
        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public String getPort() {
            return port;
        }

        public void setPort(String port) {
            this.port = port;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}
